package com.zhongshengnetwork.rightbe.lang.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.Tencent;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.SignDataModel;
import com.zhongshengnetwork.rightbe.gsonmodel.UserSignModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zhongshengnetwork.rightbe.MainActivity.REQUEST_PERMISSION;
import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class SignGoalActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private RelativeLayout share_layout;
    private ImageView header;
    private TextView name;

    private int screenWidth = 0;
    private int count = 0;

    private SignDataModel signDataModel = null;

    private Button sign_button;

    private ImageView cover;
    private TextView sign_count;
    private TextView finish_count;
    private TextView distance_count;

    private boolean needGetInfo = false;

    private KyLoadingBuilder load = null;

    private AVLoadingIndicatorView avi;

    private int signtime = 0;

    private void calculateImageWidth(){
        int width = ScreenUtils.getScreenWidth(SignGoalActivity.this);
        screenWidth = width-ScreenUtils.dip2px(SignGoalActivity.this, 0);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        signDataModel =  (SignDataModel) getIntent().getSerializableExtra("model");


        calculateImageWidth();

        setContentView(R.layout.activity_sign_goal);

        avi = (AVLoadingIndicatorView) findViewById(R.id.avi);

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more(v);
            }
        });
        topbar.setClickListener(this);

        share_layout = (RelativeLayout) findViewById(R.id.share_layout);

        needGetInfo = true;
        String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserSignTime+CommonUtils.formatString(CustomApplication.loginModel.getUid()),"");
        if (!CommonUtils.isEmpty(tdata)){
            if (CommonUtils.isToday(Long.valueOf(tdata))){
                //今天已签到
                String signData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.SignData, "");
                if (!CommonUtils.isEmpty(signData)){
                    SignDataModel m = GsonTools.getSignDataModel(signData);
                    if (m != null){
                        signDataModel = m;
                        signDataModel.setTodaySign(true);
                        needGetInfo =false;
                    }
                }
            }
        }
        if (signDataModel == null){
            signDataModel = new SignDataModel();
            signDataModel.setAll(0);
            signDataModel.setDistance(0);
            signDataModel.setFinish(0);
            signDataModel.setImg("");
            signDataModel.setText("");
            signDataModel.setTodaySign(false);
        }

        cover = (ImageView) findViewById(R.id.cover);
        ViewGroup.LayoutParams params = cover.getLayoutParams();
        params.width = screenWidth;
        params.height = Math.round(screenWidth / Configs.Value.COVER_WIDTH_HEIGHT_RATIO);
        cover.setLayoutParams(params);
        if (!CommonUtils.isEmpty(signDataModel.getImg())){
            try{
                Glide.with(SignGoalActivity.this).load(signDataModel.getImg()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }else {
            try{
                Glide.with(SignGoalActivity.this).load(CustomApplication.loginModel.getBackground()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }

        header = (ImageView) findViewById(R.id.header);
        Glide.with(SignGoalActivity.this).load(CustomApplication.loginModel.getHeader()).transform(new CircleTransform(SignGoalActivity.this)).dontAnimate().into(header);
        name = (TextView) findViewById(R.id.name);
        name.setText(CustomApplication.loginModel.getNickname());

        sign_count = (TextView) findViewById(R.id.sign_count);
        sign_count.setText(""+signDataModel.getAll());

        finish_count = (TextView) findViewById(R.id.finish_count);
        finish_count.setText(""+signDataModel.getFinish());

        distance_count = (TextView) findViewById(R.id.distance_count);
        distance_count.setText(""+signDataModel.getDistance());

        sign_button = (Button) findViewById(R.id.sign_button);
        sign_button.setClickable(true);
        sign_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signClick();
            }
        });
        updateSignButton(signDataModel.isTodaySign());

        if (needGetInfo == true){
            avi.show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final Map<String,String> map = new HashMap<String, String>();
                    map.put(APIKey.tokenKey,CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                    HttpsUtils.miniAppDo(map, "miniapp/langappid/usersign/info.do", new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    avi.hide();
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")){
                                        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.SignData, data);
                                        SignDataModel m = GsonTools.getSignDataModel(data);
                                        if (m != null){
                                            signDataModel = m;
                                            updateSignButton(signDataModel.isTodaySign());
                                            updateUI();
                                            if (signDataModel.isTodaySign() == true){
                                                signtime = (int)(System.currentTimeMillis()/1000);
                                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserSignTime+CustomApplication.loginModel.getUid(),signtime+"");
                                            }

                                        }
                                    }else {
                                        CustomApplication.showTip(commonModel, SignGoalActivity.this);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    avi.hide();
                                }
                            });
                        }
                    });
                }
            }).start();
        }


    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void more(View view){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(SignGoalActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        PermissionUtils.isPictureNote(SignGoalActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(SignGoalActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(SignGoalActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    REQUEST_PERMISSION);
                            return;
                        }
                    }else if (ActivityCompat.checkSelfPermission(SignGoalActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 申请权限
                        ActivityCompat.requestPermissions(SignGoalActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                        return;
                    }

                    final List<String> menu = new ArrayList<String>();
                    menu.add("分享");
                    menu.add("关于小目标");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(SignGoalActivity.this)
                            .builder()
                            .setTitle("")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String m : menu){
                        actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which == 1){
                                    if (signDataModel != null){
                                        Intent intent = new Intent(SignGoalActivity.this, SignShareActivity.class);
                                        Bundle bundle=new Bundle();
                                        bundle.putSerializable("model", signDataModel);//序列化
                                        intent.putExtras(bundle);//发送数据
                                        startActivity(intent);
                                    }
                                }else if (which == 2){
                                    Intent webIntent = new Intent(SignGoalActivity.this, MyWebActivity.class);
                                    webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/smartrank.do");
                                    startActivity(webIntent);
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();
                }
            }
        });

    }

    private void signClick(){

        String tdata = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.UserSignTime+CommonUtils.formatString(CustomApplication.loginModel.getUid()),"");
        if (!CommonUtils.isEmpty(tdata)){
            if (CommonUtils.isToday(Long.valueOf(tdata))){
                //今天已签到
                if (signDataModel != null){
                    Intent intent = new Intent(SignGoalActivity.this, SignShareActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("model", signDataModel);//序列化
                    intent.putExtras(bundle);//发送数据
                    startActivity(intent);
                }
                return;
            }
        }

        signtime = (int)(System.currentTimeMillis()/1000);
        avi.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey,CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        HttpsUtils.miniAppDo(map, "miniapp/langappid/usersign.do", new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            SignDataModel m = GsonTools.getSignDataModel(data);
                            if (m != null){
                                signDataModel = m;
                            }
                            updateSignButton(true);
                            updateUI();
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.SignData, data);
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserSignTime+CustomApplication.loginModel.getUid(),signtime+"");
                            UserSignModel userSignModel = GsonTools.getUserSignModel(data);
                            if (userSignModel != null){
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), userSignModel.isUnRead());
                                if (!CommonUtils.isEmpty(userSignModel.getShareUrl())){
                                    signSuccess(userSignModel);
                                }else {
                                    ToastUtil.show(SignGoalActivity.this,commonModel.getMsg());
                                }
                            }else {
                                ToastUtil.show(SignGoalActivity.this,commonModel.getMsg());
                            }
                        }else {
                            if (commonModel.getCode().equals("1000000")){
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.SignData, data);
                                SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.UserSignTime+CustomApplication.loginModel.getUid(),signtime+"");
                            }
                            ToastUtil.show(SignGoalActivity.this, commonModel.getMsg());
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                    }
                });
            }
        });

    }

    private void updateSignButton(boolean signed){
        if (signed == true){
            sign_button.setText("已签到");
            sign_button.setTextColor(Color.parseColor("#c0c0c0"));
            sign_button.setBackgroundResource(R.drawable.signed_bg);
        }else {
            sign_button.setText("签到");
            sign_button.setTextColor(Color.parseColor("#99cc00"));
            sign_button.setBackgroundResource(R.drawable.unsigned_bg);
        }
    }

    private void updateUI(){
        if (signDataModel != null){
            if (!CommonUtils.isEmpty(signDataModel.getImg())){
                try{
                    Glide.with(SignGoalActivity.this).load(signDataModel.getImg()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
                }
            }else {
                try{
                    Glide.with(SignGoalActivity.this).load(CustomApplication.loginModel.getBackground()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
                }
            }
            sign_count.setText(""+signDataModel.getAll());
            finish_count.setText(""+signDataModel.getFinish());
            distance_count.setText(""+signDataModel.getDistance());
        }
    }

    private void signSuccess(UserSignModel userSignModel){

        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(SignGoalActivity.this);
        builder.setTitle(userSignModel.getTitle());
        builder.setMessage(userSignModel.getContent());
        builder.setPositiveButton("分享", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                dialog.dismiss();
                String signData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.SignData, "");
                if (!CommonUtils.isEmpty(signData)){
                    SignDataModel signDataModel = GsonTools.getSignDataModel(signData);
                    if (signDataModel != null){
                        Intent intent = new Intent(SignGoalActivity.this, SignShareActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", signDataModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                        return;
                    }

                }
            }
        });
        builder.setNegativeButton("知道了", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

}
